﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;
using CodeRobot.Utility;
using System.Windows.Forms;

namespace CodeRobot.DAL
{
    /// <summary>
    /// .net core处理请求类
    /// </summary>
    public class ViewIndexHelper
    {

        /// <summary>
        /// 根据表名创建Index管理页面
        /// </summary>
        /// <param name="strFilePath">保存路径</param>
        /// <param name="strProjectName">项目名</param>
        /// <param name="strTableName">表名</param>
        public static void CreateViewIndexClass(string strFilePath, string strProjectName, string strTableName, string strTableComment, string strDBName)
        {
            //读取版权信息
            CodeRobot.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
            string strCompany = iniFile.GetString("COPYRIGHT", "COMPANY", "");
            string strAuthor = iniFile.GetString("COPYRIGHT", "AUTHOR", "");
            string strVersion = iniFile.GetString("COPYRIGHT", "VERSION", "");
            string strCode = iniFile.GetString("COPYRIGHT", "CODE", "");
            string strCreateDate = iniFile.GetString("BASE", "CREATE_DATE", "");
            string strTablePrefix = iniFile.GetString("BASE", "TABLE_PREFIX", "");
            string strTableNameUpper = CommonHelper.GetTableNameUpper(strTableName);

            string strPrimaryKey = CommonHelper.GetPrimaryKey(strTableName);//如：news_id

            string strAllColumnName = CommonHelper.GetAllColumnName(strTableName);
            string strAllColumnNameNotKey = CommonHelper.GetAllColumnNameNotKey(strTableName);

            string strClassName = CommonHelper.GetClassName(strTableName);//类名
            strClassName = CommonHelper.GetTableNameUpper(strClassName);
            string strTableNameSpec = CommonHelper.GetTableNameFirstLowerSecondUpper(strClassName);//如：newsTypes
            string strTableNameLower = strTableNameSpec.ToLower();//如：newstypes

            Directory.CreateDirectory(strFilePath);
            //为每个表创建一个独立目录存放
            string strTableNamePath = strFilePath + "\\" + strClassName;
            if (!Directory.Exists(strTableNamePath))
            {
                Directory.CreateDirectory(strTableNamePath);
            }
            StreamWriter sw = new StreamWriter(strTableNamePath + "\\Index.cshtml", false, Encoding.GetEncoding("utf-8"));//生成物理文件
            string strTableComment2 = CommonHelper.GetColumnKeyComment(strTableComment);

            string strImgColumnName = CommonHelper.GetImgColumnName(strDBName, strTableName);
            string strSwitchColumnName = CommonHelper.GetSwitchColumnName(strDBName, strTableName);
            string strSwitchColumnNameText = CommonHelper.GetSwitchColumnNameText(strDBName, strTableName);
            string strSwitchColumnNameText2 = CommonHelper.GetSwitchColumnNameText2(strDBName, strTableName);
            string strSortColumnName = CommonHelper.GetSortColumnName(strDBName, strTableName);

            sw.WriteLine("@{");
            sw.WriteLine("    ViewData[\"Title\"] = \"" + strTableComment2 + "列表\";");
            sw.WriteLine("    Layout = \"~/Views/Shared/_LayoutNone.cshtml\";");
            sw.WriteLine("}");
            sw.WriteLine("<div class=\"layui-fluid\">");
            sw.WriteLine("    <div class=\"layui-card\">");
            sw.WriteLine("        <div class=\"layui-form layui-card-header layuiadmin-card-header-auto\">");
            sw.WriteLine("            <div class=\"layui-form-item\">");
            //sw.WriteLine("                <div class=\"layui-inline\">");
            //sw.WriteLine("                    <div class=\"layui-input-inline\">");
            //sw.WriteLine("                        <input type=\"text\" class=\"layui-input time\" id=\"created_at\" name=\"created_at\" autocomplete=\"off\" placeholder=\"选择日期\">");
            //sw.WriteLine("                    </div>");
            //sw.WriteLine("                </div>");
            sw.WriteLine(CommonHelper.GetSearchItemList(strDBName, strTableName));
            sw.WriteLine("                <div class=\"layui-inline\">");
            sw.WriteLine("                    <button class=\"layui-btn\" lay-submit lay-filter=\"LAY-app-contlist-search\">查询</button>");
            sw.WriteLine("                    <button class=\"layui-btn layui-btn-primary\" lay-submit lay-filter=\"LAY-app-contlist-reset\">重置</button>");
            sw.WriteLine("                    <label style=\"margin-left: 10px; color: #6eae21; cursor: pointer;\" id=\"collapse\">展开<i style=\"right: -20px;\" class=\"layui-icon layui-icon-down\"></i></label>");
            sw.WriteLine("                </div>");
            sw.WriteLine("            </div>");
            sw.WriteLine("            <div class=\"layui-form-item collapse_item\" style=\"display:none;\">");
            sw.WriteLine("                <div class=\"layui-inline\">");
            sw.WriteLine("                    <label class=\"layui-form-label\">日期:</label>");
            sw.WriteLine("                    <div class=\"layui-input-inline\">");
            sw.WriteLine("                        <input type=\"text\" class=\"layui-input time\" id=\"created_at\" name=\"created_at\" placeholder=\"选择日期\" autocomplete=\"off\">");
            sw.WriteLine("                    </div>");
            sw.WriteLine("                </div>");
            sw.WriteLine("            </div>");
            sw.WriteLine("        </div>");
            sw.WriteLine("");
            sw.WriteLine("        <div class=\"layui-card-body\">");
            sw.WriteLine("            <div class=\"layui-form-item\" style=\"margin-bottom: 5px;\">");
            sw.WriteLine("              <div class=\"layui-inline\">");
            sw.WriteLine("                <button class=\"layui-btn layui-btn-sm layuiadmin-btn-list\" data-type=\"add\"><i class=\"layui-icon\">&#xe654;</i>新增" + strTableComment2 + "</button>");
            sw.WriteLine("              </div>");
            sw.WriteLine("              <div class=\"layui-inline\">");
            sw.WriteLine("                <button class=\"layui-btn layui-btn-sm layuiadmin-btn-list\" data-type=\"export\"><i class=\"layui-icon layui-icon-export\"></i>导出" + strTableComment2 + "</button>");
            sw.WriteLine("              </div>");
            sw.WriteLine("            </div>");
            sw.WriteLine("            <table id=\"LAY-app-content-list\" lay-filter=\"LAY-app-content-list\"></table>");
            sw.WriteLine("            <script type=\"text/html\" id=\"linkTpl\">");
            sw.WriteLine("                <a lay-href=\"/" + strTableNameLower + "/views/?id={{d." + strPrimaryKey + "}}\" class=\"layui-table-link\">{{ d." + strPrimaryKey + " }}</a>");
            sw.WriteLine("            </script>");
            if (!string.IsNullOrEmpty(strSwitchColumnName))
            {
                sw.WriteLine("            <script type=\"text/html\" id=\"switchTpl\">");
                sw.WriteLine("                <input type=\"checkbox\" name=\"" + strSwitchColumnName + "\" lay-skin=\"switch\" lay-text=\"" + strSwitchColumnNameText2 + "\" lay-filter=\"check_" + strSwitchColumnName + "\" value=\"{{ d." + strPrimaryKey + " }}\" data-json=\"{{ encodeURIComponent(JSON.stringify(d)) }}\" {{ d." + strSwitchColumnName + " ? 'checked' : '' }}>");
                sw.WriteLine("            </script>");
            }
            if (!string.IsNullOrEmpty(strImgColumnName))
            {
                sw.WriteLine("            <script type=\"text/html\" id=\"imgTpl\">");
                sw.WriteLine("                <a style=\"cursor: pointer\" onclick=\"preview(this);\"><img src=\"{{ d.show_" + strImgColumnName + " }}\" width=\"100\" /></a>");
                sw.WriteLine("            </script>");
            }
            sw.WriteLine("            <script type=\"text/html\" id=\"table-content-list\">");
            sw.WriteLine("                <a class=\"layui-btn layui-btn-xs\" lay-event=\"edit\"><i class=\"layui-icon layui-icon-edit\"></i>编辑</a>");
            sw.WriteLine("                <a class=\"layui-btn layui-btn-danger layui-btn-xs\" lay-event=\"del\"><i class=\"layui-icon layui-icon-delete\"></i>删除</a>");
            sw.WriteLine("            </script>");
            sw.WriteLine("        </div>");
            sw.WriteLine("    </div>");
            sw.WriteLine("</div>");
            sw.WriteLine("");
            sw.WriteLine("<script src=\"~/layuiadmin/layui/layui.js\"></script>");
            sw.WriteLine("<script src=\"~/lib/jquery/dist/jquery.js\"></script>");
            sw.WriteLine("<script>");
            sw.WriteLine("    layui.config({");
            sw.WriteLine("        base: '/layuiadmin/'");
            sw.WriteLine("    }).extend({");
            sw.WriteLine("        index: '/lib/index'");
            sw.WriteLine("    }).use(['index', 'table', 'laydate','util'], function () {");
            sw.WriteLine("        var $ = layui.$");
            sw.WriteLine("            , table = layui.table");
            sw.WriteLine("            , admin = layui.admin");
            sw.WriteLine("            , form = layui.form");
            sw.WriteLine("            , laydate = layui.laydate");
            sw.WriteLine("            , util = layui.util;");
            sw.WriteLine("");
            sw.WriteLine("        var num = 2;");
            sw.WriteLine("        lay('.time').each(function () {");
            sw.WriteLine("            laydate.render({");
            sw.WriteLine("               elem: this,");
            sw.WriteLine("               range: true");
            sw.WriteLine("            });");
            sw.WriteLine("        });");
            sw.WriteLine("");
            if (CommonHelper.GetSelectScript(strProjectName, strDBName, strTableName, strTablePrefix).Contains("admin.req"))
            {
                sw.WriteLine("        // 默认加载");
                sw.WriteLine("        $(function () {");
                // sw.WriteLine("            // 读取数据加载loading..");
                sw.WriteLine("            loading = layer.load(2, {");
                sw.WriteLine("                shade: [0.2, '#000']");
                sw.WriteLine("            });");
                sw.WriteLine(GetSelectScript(strProjectName, strDBName, strTableName, strTablePrefix));
                sw.WriteLine("        });");
                sw.WriteLine("");
            }
            sw.WriteLine("        // 加载表格数据");
            sw.WriteLine("        table.render({");
            sw.WriteLine("            elem: \"#LAY-app-content-list\",");
            sw.WriteLine("            url: \"/" + strTableNameLower + "/list\",");
            sw.WriteLine("            toolbar: false,");
            sw.WriteLine("            cols: [");
            sw.WriteLine("                [");
            sw.WriteLine(CommonHelper.GetTableColsList(strDBName, strTableName));
            sw.WriteLine("                {");
            sw.WriteLine("                    title: \"操作\",");
            sw.WriteLine("                    width: 200,");
            sw.WriteLine("                    align: \"center\",");
            sw.WriteLine("                    fixed: \"right\",");
            sw.WriteLine("                    toolbar: \"#table-content-list\"");
            sw.WriteLine("                }]");
            sw.WriteLine("            ],");
            sw.WriteLine("            page: !0,");
            sw.WriteLine("            limit: 10,");
            sw.WriteLine("            limits: [10, 20, 50, 100, 200, 500, 1000, 2000]");
            sw.WriteLine("        }),");
            sw.WriteLine("");
            sw.WriteLine("        // 右侧操作事件");
            sw.WriteLine("        table.on(\"tool(LAY-app-content-list)\", function (t) {");
            sw.WriteLine("            var " + strPrimaryKey + " = t.data." + strPrimaryKey + ";");
            // sw.WriteLine("            // console.log('id=' + " + strPrimaryKey + ");");
            sw.WriteLine("            if (\"del\" === t.event) {");
            sw.WriteLine("                layer.confirm(\"确定删除此" + strTableComment2 + "？\", function (e) {");
            sw.WriteLine("                    admin.req({");
            sw.WriteLine("                        headers: {");
            sw.WriteLine("                            'RequestVerificationToken': csrfToken");
            sw.WriteLine("                        },");
            sw.WriteLine("                        method: 'POST',");
            sw.WriteLine("                        url: '/" + strTableNameLower + "/delete/' + " + strPrimaryKey + "");
            sw.WriteLine("                        , done: function (res) {");
            // sw.WriteLine("                            // console.log(res.msg);");
            sw.WriteLine("                            t.del();");
            sw.WriteLine("                            layer.close(e);");
            sw.WriteLine("                        }");
            sw.WriteLine("                    });");
            sw.WriteLine("");
            sw.WriteLine("                });");
            sw.WriteLine("            }");
            sw.WriteLine("            else if (\"edit\" === t.event) {");
            sw.WriteLine("                layer.open({");
            sw.WriteLine("                    type: 2,");
            sw.WriteLine("                    title: \"编辑" + strTableComment2 + "-\" + " + strPrimaryKey + " ,");
            sw.WriteLine("                    content: \"/" + strTableNameLower + "/edit?id=\" + " + strPrimaryKey + ",");
            sw.WriteLine("                    maxmin: !0,");
            sw.WriteLine("                    area: [\"550px\", \"550px\"],");
            sw.WriteLine("                    btn: [\"确定\", \"取消\"],");
            sw.WriteLine("                    yes: function (e, i) {");
            sw.WriteLine("                        a = i.find(\"iframe\").contents().find(\"#layuiadmin-app-form-edit\");");
            sw.WriteLine("                        a.trigger(\"click\");");
            sw.WriteLine("                    }");
            sw.WriteLine("                })");
            sw.WriteLine("            }");
            sw.WriteLine("        }),");
            sw.WriteLine("");
            sw.WriteLine("        // 监听搜索");
            sw.WriteLine("        form.on('submit(LAY-app-contlist-search)', function (data) {");
            sw.WriteLine("            var field = data.field;");
            sw.WriteLine("            table.reload('LAY-app-content-list', {");
            sw.WriteLine("                where: field,");
            sw.WriteLine("                page: {");
            sw.WriteLine("                  curr: 1");
            sw.WriteLine("                },");
            sw.WriteLine("            });");
            sw.WriteLine("        });");
            sw.WriteLine("");
            sw.WriteLine("        // 监听重置");
            sw.WriteLine("        form.on('submit(LAY-app-contlist-reset)', function (data) {");
            sw.WriteLine("            $(\".layui-form input\").val(\"\");");
            sw.WriteLine("            $(\".layui-card-header select\").val(\"\");");
            sw.WriteLine("        });");
            sw.WriteLine("");
            // 处理开关字段
            if (!string.IsNullOrEmpty(strSwitchColumnName))
            {
                string action = strSwitchColumnName.Replace("is_", "");
                sw.WriteLine("        // 监听" + strSwitchColumnNameText + "操作");
                sw.WriteLine("        form.on('switch(check_" + strSwitchColumnName + ")', function (obj) {");
                sw.WriteLine("            var json = JSON.parse(decodeURIComponent($(this).data('json')));");
                sw.WriteLine("            admin.req({");
                sw.WriteLine("                headers: {");
                sw.WriteLine("                    'RequestVerificationToken': csrfToken");
                sw.WriteLine("                },");
                sw.WriteLine("                method: 'POST',");
                sw.WriteLine("                url: '/" + strTableNameLower + "/set" + action + "?id=' + this.value + '&status=' + obj.elem.checked");
                sw.WriteLine("                , done: function (res) {");
                sw.WriteLine("                    // console.log(`msg=${res.msg}`);");
                sw.WriteLine("                }");
                sw.WriteLine("            });");
                sw.WriteLine("            json = table.clearCacheKey(json);");
                sw.WriteLine("        });");
            }
            // 处理排序字段
            if (!string.IsNullOrEmpty(strSortColumnName))
            {
                sw.WriteLine("        // 监听排序操作");
                sw.WriteLine("        table.on('edit(LAY-app-content-list)', function (obj) {");
                sw.WriteLine("            // console.log(`obj=${JSON.stringify(obj)}`);");
                sw.WriteLine("            admin.req({");
                sw.WriteLine("                headers: {");
                sw.WriteLine("                    'RequestVerificationToken': csrfToken");
                sw.WriteLine("                },");
                sw.WriteLine("                method: 'POST',");
                sw.WriteLine("                url: '/" + strTableNameLower + "/setsort?id=' + obj.data." + strPrimaryKey + " + '&sort=' + obj.value");
                sw.WriteLine("                , done: function (res) {");
                sw.WriteLine("                    // console.log(`msg=${res.msg}`);");
                sw.WriteLine("                }");
                sw.WriteLine("            });");
                sw.WriteLine("        });");
            }
            sw.WriteLine("");
            sw.WriteLine("        var $ = layui.$, active = {");
            sw.WriteLine("            add: function () {");
            sw.WriteLine("                layer.open({");
            sw.WriteLine("                    type: 2");
            sw.WriteLine("                    , title: '新增" + strTableComment2 + "'");
            sw.WriteLine("                    ,content: '/" + strTableNameLower + "/create'");
            sw.WriteLine("                    ,maxmin: true");
            sw.WriteLine("                    ,area: ['550px', '550px']");
            sw.WriteLine("                    ,btn: ['确定', '取消']");
            sw.WriteLine("                    ,yes: function(index, layero){");
            sw.WriteLine("                        // 点击确认触发 iframe 内容中的按钮提交");
            sw.WriteLine("                        var submit = layero.find('iframe').contents().find(\"#layuiadmin-app-form-submit\");");
            sw.WriteLine("                        submit.click();");
            sw.WriteLine("                    }");
            sw.WriteLine("                });");
            sw.WriteLine("            },");
            sw.WriteLine("            export: function () {");
            sw.WriteLine("                loading = layer.load(2, {");
            sw.WriteLine("                    shade: [0.2, '#000']");
            sw.WriteLine("                });");
            sw.WriteLine("");
            sw.WriteLine("                admin.req({");
            sw.WriteLine("                    headers: {");
            sw.WriteLine("                        'RequestVerificationToken': csrfToken");
            sw.WriteLine("                    },");
            sw.WriteLine("                    method: 'POST',");
            sw.WriteLine("                    data: { " + GetSearchColumnForExport(strDBName, strTableName) + "},");
            sw.WriteLine("                    url: '/excel/export" + strTableNameLower + "'");
            sw.WriteLine("                    , done: function (res) {");
            sw.WriteLine("                        layer.close(loading);");
            sw.WriteLine("                        if(res.errcode){");
            sw.WriteLine("                            layer.open({");
            sw.WriteLine("                              title: '错误提示'");
            sw.WriteLine("                              ,type: 1");
            sw.WriteLine("                              ,content: '<div style=\"color: red; padding: 20px; \">'+ res.errcode +':'+ res.errmsg +'</div>'");
            sw.WriteLine("                              ,btn: [\"确定\"]");
            sw.WriteLine("                            });");
            sw.WriteLine("                        } else if(res.code == 0 && res.count == 0) {");
            sw.WriteLine("                            layer.msg(res.msg, {");
            sw.WriteLine("                                offset: '15px'");
            sw.WriteLine("                                , icon: 1");
            sw.WriteLine("                                , time: 2000");
            sw.WriteLine("                            });");
            sw.WriteLine("                        } else {");
            sw.WriteLine("                            location.href = res.path;");
            sw.WriteLine("                        }");
            sw.WriteLine("                      }");
            sw.WriteLine("                });");
            sw.WriteLine("            },");
            sw.WriteLine("            refresh: function () {");
            sw.WriteLine("                table.reload('LAY-app-content-list');");
            sw.WriteLine("            }");
            sw.WriteLine("        };");
            sw.WriteLine("");
            sw.WriteLine("        $('.layui-btn.layuiadmin-btn-list').on('click', function () {");
            sw.WriteLine("            var type = $(this).data('type');");
            sw.WriteLine("            active[type] ? active[type].call(this) : '';");
            sw.WriteLine("        });");
            sw.WriteLine("");
            sw.WriteLine("        $('#collapse').on('click', function () {");
            sw.WriteLine("            if (num % 2) {");
            sw.WriteLine("                $('.collapse_item').hide();");
            sw.WriteLine("                $('#collapse').html('展开<i style=\"right: -20px;\" class=\"layui-icon layui-icon-down\"></i>');");
            sw.WriteLine("            }");
            sw.WriteLine("            else {");
            sw.WriteLine("                $('.collapse_item').show();");
            sw.WriteLine("                $('#collapse').html('收起<i style=\"right: -20px;\" class=\"layui-icon layui-icon-up\"></i>');");
            sw.WriteLine("            }");
            sw.WriteLine("            num++;");
            sw.WriteLine("        });");
            sw.WriteLine("    });");
            sw.WriteLine("");
            sw.WriteLine("    // 预览图片");
            sw.WriteLine("    function preview(t) {");
            sw.WriteLine("        var t = $(t).find(\"img\");");
            sw.WriteLine("        layer.open({");
            sw.WriteLine("            type: 1,");
            sw.WriteLine("            title: '图片预览',");
            sw.WriteLine("            skin: 'layui-layer-rim',");
            sw.WriteLine("            area: ['80%', '80%'],");
            sw.WriteLine("            shadeClose: true,");
            sw.WriteLine("            end: function (index, layero) {");
            sw.WriteLine("                return false;");
            sw.WriteLine("            },");
            sw.WriteLine("            content: '<div style=\"text-align:center;padding: 20px;\"><img src=\"' + $(t).attr('src') + '\" /></div>'");
            sw.WriteLine("        });");
            sw.WriteLine("    }");
            sw.WriteLine("</script>");
            sw.Close();

        }

        /// <summary>
        /// 获取搜索字段用于导出页面
        /// </summary>
        /// <param name="strDBName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSearchColumnForExport(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释
                    string strDataType = dr["DATA_TYPE"].ToString();//注释

                    if (strColumnComment.Contains("{搜索}"))
                    {
                        string strValue = "\"" + strColumnName + "\": $(\"#" + strColumnName + "\").val(), ";
                        strReturnValue += strValue;
                    }

                    if (strColumnName == "created_at")
                    {
                        strReturnValue += "\"select_date\": $(\"#" + strColumnName + "\").val(), ";
                    }
                }
                dr.Dispose();
                cn.Close();

                if (strReturnValue.Length > 0)
                {
                    strReturnValue = strReturnValue.Substring(0, strReturnValue.Length - 2);
                }
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段", "GetSearchColumn", false);
            }

            return strReturnValue;

        }

        /// <summary>
        /// 获取默认加载下拉框填充组件
        /// </summary>
        /// <param name="strProjectName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSelectScript(string strProjectName, string strDBName, string strTableName, string strTablePrefix)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE  TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释

                    //{下拉}[ypk_exhibition_types]会展类型
                    if (strColumnComment.Contains("{下拉}"))
                    {
                        string strComment = "";
                        if (strColumnComment.Contains("["))
                        {
                            string[] splitComment = strColumnComment.Split(new char[] { '[' });
                            strComment = splitComment[1];
                        }
                        if (strComment.Contains("]"))
                        {
                            string[] splitComment = strComment.Split(new char[] { ']' });
                            strComment = splitComment[0];
                        }

                        //表名
                        string strSelectTableName = strComment;
                        string strSelectId = CommonHelper.GetPrimaryKey(strSelectTableName);
                        string strSelectName = CommonHelper.GetKeyNameForSelect(strSelectTableName);

                        strComment = strComment.Replace(strProjectName.ToLower() + "_", "");
                        string strRouterName = strComment.ToLower();//如：newstypes
                        strRouterName = strRouterName.Replace(strTablePrefix, "");
                        strRouterName = strRouterName.Replace(strTablePrefix.ToLower(), "");
                        strRouterName = strRouterName.Replace("_", "");

                        string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);
                        string strResult = strColumnName.Replace("_", "");

                        string strValue = "            \r\n";
                        strValue += "            // " + strColumnComment2 + "\r\n";
                        strValue += "            admin.req({\r\n";
                        strValue += "                url: '/" + strRouterName + "/select'\r\n";
                        strValue += "                , done: function (res) {\r\n";
                        strValue += "                    layer.close(loading);\r\n";
                        // strValue += "                    // console.log(`res={res_" + strResult + "}`);\r\n";
                        strValue += "                    $.each(res.data, function (i, item) {\r\n";
                        strValue += "                        $(\"#" + strSelectId + "\").append(\"<option value=\" + item." + strSelectId + " + \">\" + item." + strSelectName + " + \"</option>\");\r\n";
                        strValue += "                    });\r\n";
                        strValue += "                    layui.form.render('select');\r\n";
                        strValue += "                }\r\n";
                        strValue += "            });\r\n";

                        strReturnValue += strValue;
                    }
                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段列表", "GetSearchItemList", false);
            }

            return strReturnValue;

        }


        /// <summary>
        /// 获取表格显示字段列表
        /// </summary>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetTableColsList(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE  TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释

                    string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);
                    if (strColumnName == "created_at")
                    {
                        strColumnName = "format_time";
                    }

                    string strValue = "                {\r\n";
                    strValue += "                    field: \"" + strColumnName + "\",\r\n";
                    strValue += "                    title: \"" + strColumnComment2 + "\",\r\n";
                    strValue += "                    width: 150\r\n";


                    if (strColumnName == "created_at")
                    {
                        //主键和日期需要排序
                        strValue = "                {\r\n";
                        strValue += "                    field: \"format_time\",\r\n";
                        strValue += "                    title: \"创建日期\",\r\n";
                        strValue += "                    width: 180,\r\n";
                        strValue += "                    sort: !0,\r\n";
                    }
                    if (strColumnKey == "PRI")
                    {
                        //主键设置宽度
                        strValue = "                {\r\n";
                        strValue += "                    type: \"numbers\",\r\n";
                        strValue += "                    title: \"序号\",\r\n";
                        strValue += "                    width: 80\r\n";
                    }
                    if (strColumnComment.Contains("{开关}"))
                    {
                        // 开关标记支持动态更新
                        strValue = "                {\r\n";
                        strValue += "                    field: \"" + strColumnName + "\",\r\n";
                        strValue += "                    title: \"" + strColumnComment2 + "\",\r\n";
                        strValue += "                    templet: \"#switchTpl\",\r\n";
                        strValue += "                    width: 120\r\n";
                    }
                    if (strColumnComment.Contains("{图片}") || strColumnComment.Contains("头像") || strColumnName.Contains("avatar"))
                    {
                        strValue = "                {\r\n";
                        strValue += "                    field: \"" + strColumnName + "\",\r\n";
                        strValue += "                    title: \"" + strColumnComment2 + "\",\r\n";
                        strValue += "                    templet: \"#imgTpl,\"\r\n";
                        strValue += "                    width: 85\r\n";
                    }
                    strValue += "                },\r\n";

                    strReturnValue += strValue;

                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段列表", "GetSearchItemList", false);
            }

            return strReturnValue;

        }



    }
}
